

import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';
import {customToolbarCommand} from './customToolbarCommand';

import imageIcon from '@ckeditor/ckeditor5-core/theme/icons/image.svg';


export default class customToolbar extends Plugin {
	init() {
		const editor 		= this.editor;
		const items      	= editor.config.get(( 'customToolbar.items' ))
		if(typeof items != 'array'){
			return
		}

		for (let i=0; i<items.length; i++){
			const name  		= items[i].name;
			const callback 		= this._safeGet(items[i].callback, function () {
			});

			let   icon	 	= this._safeGet(items[i].icon, imageIcon);


			//---command
			const com =  'custom-toolbar-'+name;
			editor.commands.add( com, new customToolbarCommand( editor,callback ) );

			//---toolbar
			this._createToolbarButton(com, icon);

		}

	}


	_createToolbarButton(name, tbicon) {
		const editor = this.editor;

		editor.ui.componentFactory.add( name, locale => {
			const button = new ButtonView( locale );
			const command = editor.commands.get( name );


			button.isEnabled = true;
			button.isOn      = true;
			button.label     = name;
			button.tooltip   = true;
			button.icon		 = tbicon;

			button.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' );
			this.listenTo( button, 'execute', () => editor.execute( name ) );

			return button;
		} );
	}


	_safeGet(input, safeDefault){
		if( typeof input !== 'undefined' &&  (input || input===false || input===0) ){
			return input;
		}
		else{
			return safeDefault;
		}
	}
}
